#include "CSetSpriteFileCommand.h"
#include "CUserInterface.h"
#include "CLevelEditor.h"
#include "CAnimatedBillboardSceneNode.h"

extern CGlobals* g;
extern CUserInterface* ui;
extern CLevelEditor* editor;

CSetSpriteFileCommand::CSetSpriteFileCommand (int id, stringw newSpriteFile)
{
	m_id = id;
	CSceneObject* obj = editor->getSceneObjectFromID(id);
	m_oldAnim = obj->m_UserData->getAttributeAsInt("CurrentAnim");
	m_oldSpriteFile = obj->m_UserData->getAttributeAsStringW("SpriteFile");
	m_newSpriteFile = newSpriteFile;
	setDescription(L"change SpriteFile");
}

void CSetSpriteFileCommand::redo ()
{
	CSceneObject* obj = editor->getSceneObjectFromID(m_id);
	obj->m_UserData->setAttribute("SpriteFile", m_newSpriteFile.c_str());
	CAnimatedBillboardSceneNode* animatedBillboard = dynamic_cast<CAnimatedBillboardSceneNode*>(obj->m_SceneNode);
	animatedBillboard->LoadSprite(stringc(m_newSpriteFile.c_str()).c_str());
	
	if(obj->m_UserData->getAttributeAsStringW("SpriteTexture") != L"")
	{
		animatedBillboard->LoadTexture(stringc(obj->m_UserData->getAttributeAsStringW("SpriteTexture").c_str()).c_str());
	}
	
		obj->m_UserData->setAttribute("CurrentAnim", 0);
	if(animatedBillboard->m_spriteInstance) 
		animatedBillboard->m_spriteInstance->SetAnim(0);
	editor->setSelectedNode(obj->m_SceneNode);
	ui->createSelectedObjectProperties();
}

void CSetSpriteFileCommand::undo ()
{
	CSceneObject* obj = editor->getSceneObjectFromID(m_id);
	obj->m_UserData->setAttribute("SpriteFile", m_oldSpriteFile.c_str());
	CAnimatedBillboardSceneNode* animatedBillboard = dynamic_cast<CAnimatedBillboardSceneNode*>(obj->m_SceneNode);
	animatedBillboard->LoadSprite(stringc(m_oldSpriteFile.c_str()).c_str());
	obj->m_UserData->setAttribute("CurrentAnim", m_oldAnim);
	if(animatedBillboard->m_spriteInstance) 
		animatedBillboard->m_spriteInstance->SetAnim(m_oldAnim);
	if(obj->m_UserData->getAttributeAsStringW("SpriteTexture") != L"")
	{
		animatedBillboard->LoadTexture(stringc(obj->m_UserData->getAttributeAsStringW("SpriteTexture").c_str()).c_str());
	}

	editor->setSelectedNode(obj->m_SceneNode);
	ui->createSelectedObjectProperties();
}
